<!-- 状态监控 -->
<script setup lang="ts">
import type { EditTrainBasicInfo, ViewBasicInfo, ViewInfo } from "@/common/apis/train/type"
import { endTaskApi, getTaskInfoApi, pauseTaskApi, startTaskApi } from "@/common/apis/train"
import { TaskStaticsTypeEnum } from "@/common/constants/other-keys"
import { defineProps, onActivated, onMounted, ref, watch } from "vue"
import TrainChart from "./trainChart.vue"
import TrainFile from "./trainFile.vue"


interface Props {
  ruleForm: EditTrainBasicInfo
}
const props = defineProps<Props>()
let timer: number | null = null
const route = useRoute()
const formData = ref<ViewBasicInfo>()
const maxRound = ref<number>(0)
const progressTask = ref<number>(0)
const isPlay = ref(false)
const single_round_duration = ref<number>(0)
const used_worker_num = ref<number>(0)
const remaining_worker_num = ref<number>(0)
const TrainChartRef = ref()
const TrainFileRef = ref()
const taskId = ref<string>(route.query.id as string)
const playLoading = ref<boolean>(false)

function getTaskInfo() {
  if (!taskId.value) return
  getTaskInfoApi(taskId.value).then((res) => {
    const data: ViewInfo = res.data as ViewInfo
    formData.value = {
      task_id: data.task_id,
      task_name: data.task_name,
      task_process: data.task_process,
      task_status: data.task_status,
      task_round: data.task_round,
      total_duration: data.total_duration
    }
    if (data.train_config && data.train_config.episode_config) {
      maxRound.value = Number(data.train_config.episode_config.max_episode)
    }
    progressTask.value = Number(data.task_process)
    if (Number(data.task_process) > 0 || data.task_status == TaskStaticsTypeEnum.RUNNING) {
      isPlay.value = true
    }
    if (data.task_status == TaskStaticsTypeEnum.FINISHED) {
      progressTask.value > 0 ? 100 : progressTask.value
      isPlay.value = false
    }
  })
}
// 播放
function handlePlay() {
  if (props.ruleForm.agent_config.red.length === 0 && props.ruleForm.agent_config.blue.length === 0) {
    ElMessage.warning("请先选择Agent")
    return
  }
  if (!(props.ruleForm.sim_config.engine_id && props.ruleForm.sim_config.scn_id)) {
    ElMessage.warning("请先选择引擎和想定")
    return
  }
  if (formData.value?.task_status == 1) return
  playLoading.value = true
  startTaskApi(taskId.value)
    .then(() => {
      isPlay.value = true
      getTaskInfo()
      TrainFileRef.value.restart()
      TrainChartRef.value.restart()
    })
    .finally(() => {
      playLoading.value = false
    })
}
// 暂停
function handlePause() {
  if (formData.value?.task_status == 1) return
  playLoading.value = true
  pauseTaskApi(taskId.value)
    .then(() => {
      isPlay.value = false
      getTaskInfo()
    })
    .finally(() => {
      playLoading.value = false
    })
}
// 停止
function handleStop() {
  if (formData.value?.task_status == 0 || formData.value?.task_status == 2 || formData.value?.task_status == 3 || !isPlay.value) return
  playLoading.value = true
  endTaskApi(taskId.value)
    .then(() => {
      isPlay.value = false
      getTaskInfo()
    })
    .finally(() => {
      playLoading.value = false
    })
}

watch(
  () => props.type,
  () => {
    if (props.type == "type") {
      nextTick(() => {
        TrainChartRef.value && TrainChartRef.value.resize()
      })
    }
  },
  { immediate: true, deep: true }
)

function refresh() {
  if (formData.value?.task_status == 1) {
    getTaskInfo()
  }
}

onActivated(() => {
  getTaskInfo()
})

onMounted(() => {
  getTaskInfo()
  timer = Number(setInterval(refresh, 1000 * 30))
})
onBeforeUnmount(() => {
  timer && clearInterval(timer)
})
</script>

<template>
  <div class="tab-content">

    <div class="content-item">
      <div class="content-item-status">
        <div class="cpi-header-title">
          <SvgIcon name="config-title" />
          <span class="cpi-header-text">任务执行</span>
        </div>
        <div class="engine-config-title">
          <SvgIcon name="info-little-title" />
          <span class="cpi-header-text">任务状态</span>
          {{ playLoading ? "(任务初始化中...)" : "" }}
        </div>
        <div class="task-status-header">
          <div>
            已运行时间：
            {{
              `${formData?.total_duration?.[0] ?? 0
              }时${formData?.total_duration?.[1] ?? 0
              }分${formData?.total_duration?.[2] ?? 0
              }秒`
            }}
          </div>
          <div>剩余运行时间：{{ single_round_duration }}分钟</div>
          <div>局数：{{ `${formData?.task_round} / ${maxRound}` }} 局</div>
          <div>Worker运行数量：{{ used_worker_num }}</div>
          <div>Worker空闲数量：{{ remaining_worker_num }}</div>
        </div>
        <div class="task-status-control">
          <el-progress :percentage="progressTask == 0 && formData?.task_status == 1 ? 100 : progressTask"
            :stroke-width="18" :show-text="false" :status="progressTask == 100 ? '' : 'warning'"
            :striped="progressTask != 100" :striped-flow="progressTask != 100" :duration="progressTask == 100 ? 0 : 20"
            :color="progressTask == 0 && formData?.task_status == 1 ? 'rgba(64, 158, 255, 0.1)' : ''" style="flex: 1" />
          <div v-loading="playLoading" class="control-btn">
            <el-tooltip v-if="!isPlay" class="box-item" effect="dark"
              :content="(formData?.task_status == 2 || formData?.task_status == 3) ? '已完成项目将被清空，是否继续执行' : '开始'">
              <div text :disabled="formData?.task_status == 1" :class="{ 'is-disabled': formData?.task_status == 1 }"
                @click="() => handlePlay()">
                <el-space>
                  <SvgIcon name="video-start" class="svg-icon success" />
                </el-space>
              </div>
            </el-tooltip>
            <el-tooltip v-else class="box-item" effect="dark" content="暂停">
              <div text :disabled="formData?.task_status == 1" :class="{ 'is-disabled': formData?.task_status == 1 }"
                @click="() => handlePause()">
                <el-space>
                  <SvgIcon name="video-pause" class="svg-icon primary" />
                </el-space>
              </div>
            </el-tooltip>
            <el-tooltip effect="dark" content="停止">
              <div class="box-item" text title="点击直接结束任务"
                :class="{ 'is-disabled': formData?.task_status == 0 || formData?.task_status == 2 || formData?.task_status == 3 || !isPlay }"
                :disabled="formData?.task_status == 0 || formData?.task_status == 2 || formData?.task_status == 3 || !isPlay"
                @click="() => handleStop()">
                <el-space>
                  <SvgIcon name="video-stop" class="svg-icon danger" />
                </el-space>
              </div>
            </el-tooltip>
          </div>
        </div>
        <div class="cpi-header-title">
          <SvgIcon name="info-little-title" />
          <span class="cpi-header-text">任务曲线</span>
        </div>
        <TrainChart ref="TrainChartRef" :max-round="maxRound" :task-status="formData?.task_status"
          v-model:used-worker-num="used_worker_num" v-model:remaining-worker-num="remaining_worker_num" />
        <div class="cpi-header-title">
          <SvgIcon name="info-little-title" />
          <span class="cpi-header-text">任务文件</span>
        </div>
        <TrainFile ref="TrainFileRef" :task-status="formData?.task_status" />
      </div>
    </div>

  </div>
</template>

<style lang="scss" scoped>
.tab-content {
  width: calc(100%);
  height: calc(100%);
}

.content-item {
  padding: 0 10px;
  margin-bottom: var(--main-padding);
}

.content-item-status {
  background: var(--el-bg-color);
  border-radius: 4px 4px 4px 4px;
  padding: var(--main-padding);
}

.cpi-header-title {
  margin-bottom: 20px;
}

.task-status-header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  &>div {
    height: 32px;
    line-height: 32px;
    margin-right: 100px;
  }
}

.task-status-control {
  width: 100%;
  display: flex;
  flex-direction: row;
  gap: 20px;


}

.control-btn {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: var(--main-padding);

  .box-item {
    height: 56px !important;
    padding: 0 !important;
  }
}

.box-item.is-disabled {
  .svg-icon {
    cursor: not-allowed;

    &.success {
      fill: rgba(148.6, 212.3, 117.1, 0.3) !important;
    }

    &.primary {
      fill: rgb(121.3, 187.1, 255, 0.3) !important;
    }

    &.danger {
      fill: rgb(248, 152.1, 152.1, 0.3) !important;
    }
  }
}

.svg-icon {
  width: 56px !important;
  height: 56px !important;
  cursor: pointer;

  &.success {
    fill: rgb(148.6, 212.3, 117.1) !important;
  }

  &.primary {
    fill: rgb(121.3, 187.1, 255) !important;
  }

  &.danger {
    fill: rgb(248, 152.1, 152.1) !important;
  }
}

@media screen and (max-width: 600px) {
  .task-status-control {
    display: flex;
    flex-direction: column;
  }
}
.cpi-header-text {
  margin-left: 6px;
}
</style>
